package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class ChangePassword
 */
public class ChangePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChangePassword() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Changes the password of a registered user
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int result;
		boolean changePasswordSuccess = false;
		String username;
		String f_oldPassword;
		PreparedStatement stmt = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();

		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				ResultSet rs;
				String hashedPassword;
				if (f_requestType.equals("Web")) {
					username = (String) request.getSession().getAttribute("username");
				} else {
					username = request.getParameter("username");
				}
				/*
				 * Old password of the user is also required to make sure it is actually that user who is
				 * trying to change the password
				 */
				f_oldPassword = request.getParameter("old_password");
				// Get the password encoded in SHA-256
				hashedPassword = Utilities.hashPassword(f_oldPassword);
				stmt = conn.prepareStatement("SELECT * FROM "
						+ TableNames.USERS_TABLE
						+ " WHERE username = ? and password = ?");
				stmt.setString(1, username);
				stmt.setString(2, hashedPassword);
				rs = stmt.executeQuery();

				/*
				 * If user credentials are correct, then perform the password update operation. Otherwise do
				 * not carry out the operation and generate an error message.
				 */
				if (rs.next()) {
					String f_newPassword = request.getParameter("new_password");
					hashedPassword = Utilities.hashPassword(f_newPassword);
					stmt = conn.prepareStatement("UPDATE "
							+ TableNames.USERS_TABLE
							+ " SET password = ? WHERE username = ?");
					stmt.setString(1, hashedPassword);
					stmt.setString(2, username);
					result = stmt.executeUpdate();
					if (result == 1) {
						changePasswordSuccess = true;
					}
				}
				/*
				 * Based on the source of the request (Web or Android client) different responses are created.
				 * Android clients are returned a JSONObject while Web clients are returned a HTTPServletResponse
				 * object.
				 */
				if (f_requestType.equals("Web")) {
					request.setAttribute("changePasswordSuccess", changePasswordSuccess);
					// Redirect the user to his profile page after the operation
					request.getRequestDispatcher("GetProfile").forward(request, response);
				} else if (f_requestType.equals("Android")) {
					JSONObject changePasswordResultJsonObject = new JSONObject();
					try {
						changePasswordResultJsonObject.put("changePasswordSuccess", changePasswordSuccess);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(changePasswordResultJsonObject.toString());
				} else {
					// HANDLE?
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
